package com.EAsystem.controller.admin;

import com.EAsystem.annotation.RequireRole;
import com.EAsystem.entity.Homework;
import com.EAsystem.entity.HomeworkSubmission;
import com.EAsystem.service.HomeworkSubmissionService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/admin")
@RequireRole({1}) // 只有管理员可以访问
public class HomeworkSubmissionController {

    @Autowired
    private HomeworkSubmissionService homeworkSubmissionService;

    /**
     * 作业提交管理页面
     */
    @GetMapping("/homework")
    public String homeworkSubmissionPage(@RequestParam(defaultValue = "1") int page,
                                       @RequestParam(defaultValue = "5") int size,
                                       @RequestParam(required = false) String homeworkTitle,
                                       Model model) {
        
        PageInfo<HomeworkSubmission> pageInfo;
        
        // 根据条件查询
        if (homeworkTitle != null && !homeworkTitle.trim().isEmpty()) {
            HomeworkSubmission searchHomeworkSubmission = new HomeworkSubmission();
            Homework homework = new Homework();
            homework.setTitle(homeworkTitle.trim());
            searchHomeworkSubmission.setHomework(homework);
            pageInfo = homeworkSubmissionService.getHomeworkSubmissionsByConditionWithPage(searchHomeworkSubmission, page, size);
        } else {
            pageInfo = homeworkSubmissionService.getAllHomeworkSubmissionsWithPage(page, size);
        }

        List<Integer> pageNumbers = new ArrayList<>();
        for (int i = 1; i <= pageInfo.getPages(); i++) {
            pageNumbers.add(i);
        }
        
        model.addAttribute("homeworkSubmissions", pageInfo.getList());
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("totalRecords", pageInfo.getTotal());
        model.addAttribute("searchHomeworkTitle", homeworkTitle);
        model.addAttribute("pageNumbers", pageNumbers);
        
        return "admin/homework";
    }

    /**
     * 查看作业提交详情
     */
    @GetMapping("/homework/submission/view/{id}")
    @ResponseBody
    public Map<String, Object> viewHomeworkSubmission(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            HomeworkSubmission submission = homeworkSubmissionService.getHomeworkSubmissionById(id);
            if (submission != null) {
                result.put("success", true);
                result.put("submission", submission);
            } else {
                result.put("success", false);
                result.put("message", "未找到作业提交");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取作业提交失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 作业打分
     */
    @PostMapping("/homework/grade/{id}")
    @ResponseBody
    public Map<String, Object> gradeHomeworkSubmission(@PathVariable Long id, 
                                                      @RequestParam Double score) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (score < 0 || score > 100) {
                result.put("success", false);
                result.put("message", "分数必须在0-100之间");
                return result;
            }
            
            boolean success = homeworkSubmissionService.gradeHomeworkSubmission(id, score);
            if (success) {
                result.put("success", true);
                result.put("message", "打分成功");
            } else {
                result.put("success", false);
                result.put("message", "打分失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "打分失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 删除作业提交
     */
    @GetMapping("/homework/submission/delete/{id}")
    public String deleteHomeworkSubmission(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            boolean success = homeworkSubmissionService.deleteHomeworkSubmission(id);
            if (success) {
                redirectAttributes.addFlashAttribute("message", "删除成功");
            } else {
                redirectAttributes.addFlashAttribute("error", "删除失败");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "删除失败：" + e.getMessage());
        }
        return "redirect:/admin/homework-submissions";
    }

    /**
     * 批量删除作业提交
     */
    @GetMapping("/homework/batchDelete")
    public String batchDeleteHomeworkSubmissions(@RequestParam("ids") String ids) {
        if (ids != null && !ids.isEmpty()) {
            for (String id : ids.split(",")) {
                try {
                    homeworkSubmissionService.deleteHomeworkSubmission(Long.valueOf(id));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
        return "redirect:/admin/homework";
    }

    /**
     * 下载作业文件
     */
    @GetMapping("/homework/download/{id}")
    public void downloadHomeworkFile(@PathVariable Long id, 
                                   HttpServletRequest request,
                                   HttpServletResponse response) {
        try {
            HomeworkSubmission homeworkSubmission = homeworkSubmissionService.getHomeworkSubmissionById(id);
            if (homeworkSubmission == null || homeworkSubmission.getFileUrl() == null || homeworkSubmission.getFileUrl().trim().isEmpty()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().write("<script>alert('文件不存在');history.back();</script>");
                return;
            }
            
            String fileUrl = homeworkSubmission.getFileUrl().trim();
            String fileName = "作业文件_" + id;

            if (fileUrl.toLowerCase().contains(".pdf")) {
                fileName += ".pdf";
                response.setContentType("application/pdf");
            } else if (fileUrl.toLowerCase().contains(".doc")) {
                fileName += ".doc";
                response.setContentType("application/msword");
            } else if (fileUrl.toLowerCase().contains(".docx")) {
                fileName += ".docx";
                response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            } else if (fileUrl.toLowerCase().contains(".txt")) {
                fileName += ".txt";
                response.setContentType("text/plain");
            } else if (fileUrl.toLowerCase().contains(".zip")) {
                fileName += ".zip";
                response.setContentType("application/zip");
            } else if (fileUrl.toLowerCase().contains(".jpg") || fileUrl.toLowerCase().contains(".jpeg")) {
                fileName += ".jpg";
                response.setContentType("image/jpeg");
            } else if (fileUrl.toLowerCase().contains(".png")) {
                fileName += ".png";
                response.setContentType("image/png");
            } else {
                fileName += ".txt";
                response.setContentType("application/octet-stream");
            }
            
            // 设置下载头信息
            response.setHeader("Content-Disposition", "attachment; filename=\"" + 
                new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + "\"");

            // fileUrl是一个完整的URL，重定向到该URL
            if (fileUrl.startsWith("http://") || fileUrl.startsWith("https://")) {
                response.sendRedirect(fileUrl);
                return;
            }
            
            // 尝试从项目根目录读取文件
            String webAppRoot = System.getProperty("user.dir");
            java.io.File file = new java.io.File(webAppRoot + java.io.File.separator + fileUrl.replace("/", java.io.File.separator));
            
            if (file.exists() && file.isFile()) {
                // 读取文件并输出到响应流
                try (java.io.FileInputStream fis = new java.io.FileInputStream(file);
                     java.io.OutputStream os = response.getOutputStream()) {
                    
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = fis.read(buffer)) != -1) {
                        os.write(buffer, 0, bytesRead);
                    }
                    os.flush();
                }
            } else {
                // 文件不存在，创建一个示例文件内容
                response.setContentType("text/plain;charset=UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=\"" + 
                    new String(("作业文件_" + id + ".txt").getBytes("UTF-8"), "ISO-8859-1") + "\"");
                
                String content = "作业提交文件\n";
                content += "提交ID: " + id + "\n";
                content += "学生: " + (homeworkSubmission.getStudent() != null && 
                           homeworkSubmission.getStudent().getUser() != null ? 
                           homeworkSubmission.getStudent().getUser().getRealName() : "未知") + "\n";
                content += "作业: " + (homeworkSubmission.getHomework() != null ? 
                           homeworkSubmission.getHomework().getTitle() : "未知") + "\n";
                content += "说明: " + (homeworkSubmission.getContent() != null ? 
                           homeworkSubmission.getContent() : "无") + "\n";
                content += "原文件路径: " + fileUrl + "\n";
                content += "\n注意：这是一个示例文件，实际文件可能已丢失或路径不正确。";
                
                response.getWriter().write(content);
            }
            
        } catch (Exception e) {
            try {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().write("<script>alert('下载失败：" + e.getMessage() + "');history.back();</script>");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }


} 